<template>
  <u-navbar
    back-text=""
    title=""
    :background="navBackground"
    back-icon-size="30rpx"
    :is-fixed="true"
    :immersive="true"
    title-color="#fff"
    back-icon-color="#fff"></u-navbar>
	<view>
		<img class="bg" src="/pages/objIdentify/static/image/obj-identify/bg.jpg" />
		<view class="container">
			<canvas type="webgl" id="webgl" @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd"
				:style="{ width: canvasWidth + 'px', height: canvasHeight + 'px', display: 'block' }">
			</canvas>

			<view class="btns">
				<img class="check-btn1" src="/pages/objIdentify/static/image/obj-identify/check-btn-1.png"
					@click="check1();" v-show="!curBtn1">
				<img class="check-btn1" src="/pages/objIdentify/static/image/obj-identify/check-btn-1-hover.png"
					@click="check1();" v-show="curBtn1">

				<img class="check-btn2" src="/pages/objIdentify/static/image/obj-identify/check-btn-2.png"
					@click="check2();" v-show="!curBtn2">
				<img class="check-btn2" src="/pages/objIdentify/static/image/obj-identify/check-btn-2-hover.png"
					@click="check2();" v-show="curBtn2">

				<img class="check-btn3" src="/pages/objIdentify/static/image/obj-identify/check-btn-3.png"
					@click="check3();" v-show="!curBtn3">
				<img class="check-btn3" src="/pages/objIdentify/static/image/obj-identify/check-btn-3-hover.png"
					@click="check3();" v-show="curBtn3">
			</view>

			<view class="obj-name">
				{{ objInfo === null ? "" : objInfo.name }}
			</view>

			<view class="obj-describe">
				{{ curBtn2 ? objInfo.useExplain : '' }}
			</view>

			<view class="base-3d-container webgl">
				<view class="base-3d-camera webgl"
					:style="{ transform: cameraTransformStyle, perspective: perspectivePx }">
					<view class="base-3d-object" :style="labelStyle1">
						<view class="description-text"> {{ labelText1 }}</view>
					</view>
					<view class="base-3d-object" :style="labelStyle2">
						<view class="description-text"> {{ labelText2 }}</view>
					</view>
					<view class="base-3d-object" :style="labelStyle3">
						<view class="description-text"> {{ labelText3 }}</view>
					</view>
					<view class="base-3d-object" :style="labelStyle4">
						<view class="description-text"> {{ labelText4 }}</view>
					</view>
				</view>
			</view>

		</view>

	</view>
</template>

<script>
import api from '@/config/api'
import { getFireFacilityDetail } from '@/api/objIdentify'

import * as THREE from './threeWechat/build/three.module.js';
import { WechatPlatform } from './threeWechat/build/WechatPlatform.js';

import {
	OrbitControls
} from './threeWechat/examples/jsm/controls/OrbitControls.js';

import { Logic } from "./threeWechat/costum/Logic.js";

import {
	CSS3DRenderer,
} from "./threeWechat/costum/CssRender.js";

let renderer, camera, scene, controls, platForm, css3dRenderer;
let logic, lastDate = new Date().getTime();
const dispatcher = {
	ready: false,
	_dispatchLoadedFuncs: [],
	_dispatchModelLoadedPromise() {
		this._dispatchLoadedFuncs.forEach(promiseResolveFunc => {
			promiseResolveFunc && promiseResolveFunc();
		});

		this.ready = true;
	},
	readyPromise: function () {
		return new Promise((resolve) => {
			if (this.ready === false) {
				this._dispatchLoadedFuncs.push(() => {
					resolve(logic);
				});
			} else {
				return resolve(logic);
			}
		});
	}
};
import uNavbar from '@/components/navbar/index.vue'
export default {
	data() {
		return {
			canvasWidth: 375,
			canvasHeight: 600,
			canvas: null,
			animation: null,
			modelUrl: api.modelUrl, //三维模型请求地址前缀
			curObjId: "",
			curBtn1: true,
			curBtn2: false,
			curBtn3: false,
			textVisible: false,
			// btnImageUrl1: "/pages/objIdentify/static/image/obj-identify/check-btn-1.png",
			// btnImageUrlActive1: "/pages/objIdentify/static/image/obj-identify/check-btn-1-hover.png",
			// btnImageUrl2: "/pages/objIdentify/static/image/obj-identify/check-btn-2.png",
			// btnImageUrlActive2: "/pages/objIdentify/static/image/obj-identify/check-btn-2-hover.png",
			// btnImageUrl3: "/pages/objIdentify/static/image/obj-identify/check-btn-3.png",
			// btnImageUrlActive3: "/pages/objIdentify/static/image/obj-identify/check-btn-3-hover.png",			
			objInfo: null,
			labelStyle1: { display: "none" },
			labelStyle2: { display: "none" },
			labelStyle3: { display: "none" },
			labelStyle4: { display: "none" },
			labelText1: "",
			labelText2: "",
			labelText3: "",
			labelText4: "",
			cameraTransformStyle: "",
      perspectivePx: "0px",
      navBackground: {
        background: 'transparent'
      }
		}
  },
  components: {
    uNavbar
  },
	onLoad(option) {

		this.curObjId = option.curObjId || "1";
		console.log("=======获取到设备id======", this.curObjId);

		this.getObjInfo();

		this.check1();

		// 获取设备信息以设置画布大小
		const info = uni.getSystemInfoSync();
		this.canvasWidth = info.windowWidth;
		this.canvasHeight = info.windowHeight;

		// console.log(this.canvasWidth, this.canvasHeight);

		// 初始化3D场景
		this.$nextTick(async () => {

			uni.showLoading({
				title: '加载中',
				mask: true,
			});

			await this.initThree();

			logic = new Logic(camera, scene, controls, {
				textChangedCallback: (label, index, text) => {
					this['labelText' + index] = text;
				},
				modelUrl: this.modelUrl
			});
			logic.setResolution(this.canvasWidth, this.canvasHeight);
			dispatcher._dispatchModelLoadedPromise();


		});

	},
	onUnload() {
		this.cleanupThreeJS();
	},
	methods: {

		initThree() {
			return new Promise((resolve) => {
				// 获取canvas上下文
				const query = uni.createSelectorQuery().in(this);
				query.select('#webgl')
					.node()
					.exec((res) => {
						const canvas = res[0].node;
						this.canvas = canvas;
						platForm = new WechatPlatform(canvas, this.canvasWidth, this.canvasHeight)
						THREE.PLATFORM.set(platForm);

						// 创建渲染器
						renderer = new THREE.WebGLRenderer({
							canvas: canvas,
							antialias: true,
							alpha: true,
						});

						const info = uni.getSystemInfoSync();
						this.canvasWidth = info.windowWidth;
						this.canvasHeight = info.windowHeight;

						renderer.outputEncoding = THREE.sRGBEncoding;
						renderer.setSize(this.canvasWidth, this.canvasHeight);
						renderer.setPixelRatio(uni.getSystemInfoSync().pixelRatio);
						renderer.setClearAlpha(0);
						renderer.setClearColor(0xaaaaaa, 0);

						// 创建场景
						scene = new THREE.Scene();
						// scene.background = new THREE.Color(0x000000);

						// 创建相机
						camera = new THREE.PerspectiveCamera(
							75,
							this.canvasWidth / this.canvasHeight,
							1,
							10000
						);
						camera.position.set(100, 100, 100);
						// scene.add(new THREE.AxesHelper(100));
						// 创建控制器
						controls = new OrbitControls(camera, canvas);
						controls.enableDamping = false;

						// 添加光源
						const ambientLight = new THREE.AmbientLight(0xffffff, 1.0);
						scene.add(ambientLight);

						const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
						directionalLight.position.set(1, 1, 1);
						scene.add(directionalLight);

						const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1);
						directionalLight.position.set(-1, 1, -1);
						scene.add(directionalLight1);

						// 创建css3drenderer
						css3dRenderer = new CSS3DRenderer({
							setCameraStyle: ({
								perspective,
								transform
							}) => {
								if (perspective) {
									this.perspectivePx = perspective;
								}

								if (transform) {
									this.cameraTransformStyle = transform;
								}
							},

							setObjectStyle: (object, {
								transform,
								display
							}) => {
								const style = {
									transform,
									display
								};
								if (object.elementId === 1) {
									this.labelStyle1 = style;
								}
								if (object.elementId === 2) {
									this.labelStyle2 = style;
								}
								if (object.elementId === 3) {
									this.labelStyle3 = style;
								}
								if (object.elementId === 4) {
									this.labelStyle4 = style;
								}

							},

						});

						css3dRenderer.setSize(this.canvasWidth, this.canvasHeight);
						// this.createSuffix();
						// 开始动画循环
						this.animate();

						// window.addEventListener('resize', onWindowResize);

						resolve();
					});
			});
		},

		cleanupThreeJS(fullClean = true) {
			dispatcher._dispatchLoadedFuncs.length = 0;
			dispatcher.ready = false;
			if (scene) {
				// 清理场景中的对象
				while (scene.children.length) {
					const obj = scene.children[0]
					if (obj.geometry) obj.geometry.dispose()
					if (obj.material) obj.material.dispose()
					scene.remove(obj)
				}
				scene = null
				camera = null
			}

			if (this.animation !== undefined && this.animation !== null && this.canvas) {
				this.canvas.cancelAnimationFrame(this.animation);
				this.animation = null;
				this.canvas = null;
			}

			if (fullClean && renderer) {
				// 完全卸载时清理渲染器
				renderer.dispose()
				renderer.forceContextLoss()
				renderer.domElement = null
				renderer = null;
			}
		},

		onWindowResize() {
			const info = uni.getSystemInfoSync();
			this.canvasWidth = info.windowWidth;
			this.canvasHeight = info.windowHeight;
		},

		animate() {
			const date = new Date().getTime();
			const delta = date - lastDate;
			lastDate = date;

			this.animation = this.canvas.requestAnimationFrame(() => {
				this.animate();
			});

			// 更新控制器
			if (controls) {
				controls.update();
			}

			// 渲染场景
			if (renderer && scene && camera) {
				renderer.render(scene, camera);
			}

			if (css3dRenderer && scene && camera) {
				css3dRenderer.render(scene, camera);
			}

			if (logic) {
				logic.onTick(delta);
			}
		},

		// 触摸事件处理
		onTouchStart(event) {
			platForm.dispatchTouchEvent(event)

			// 在这里处理触摸开始事件
		},

		onTouchMove(event) {
			platForm.dispatchTouchEvent(event)

			// 在这里处理触摸移动事件
		},

		onTouchEnd(event) {
			platForm.dispatchTouchEvent(event)
			// 在这里处理触摸结束事件
		},

		check1() {
			this.curBtn1 = true;
			this.curBtn2 = false;
			this.curBtn3 = false;
			this.indexType = 1;

			dispatcher.readyPromise().then(async (logic) => {
				await logic.loadData(this.indexType, null);
			});
		},

		check2() {
			this.curBtn1 = false;
			this.curBtn2 = true;
			this.curBtn3 = false;
			this.indexType = 2;

			dispatcher.readyPromise().then((logic) => {
				logic.loadData(this.indexType, null);
			});
		},

		check3() {
			this.curBtn1 = false;
			this.curBtn2 = false;
			this.curBtn3 = true;
			this.indexType = 3;

			dispatcher.readyPromise().then((logic) => {
				logic.loadData(this.indexType, null);
			});
		},

		getObjInfo() {
			getFireFacilityDetail(this.curObjId).then(res => {
				console.log(res);
				if (res.data.code == 200) {
					this.objInfo = res.data.result;
				}
			}).catch((error) => {
				console.log(error)
			});
		},

	},

	watch: {
		objInfo(newValue) {
			dispatcher.readyPromise().then((logic) => {
				logic.loadData(this.indexType, newValue);
			});
		},
	},
}
</script>

<style>
.arrow-icon {
	display: inline-block;
	width: 24px;
	/* 控制整体大小 */
	height: 24px;
	cursor: pointer;

	position: absolute;
	top: 55px;
	left: 10px;
	z-index: 99;
	color: #ffffff;
}

/* 通过旋转矩形创建箭头线条 */
.arrow-icon::before {
	content: '';
	position: absolute;
	top: 50%;
	left: 25%;
	width: 12px;
	/* 控制箭头长度 */
	height: 2px;
	/* 控制线条粗细 */
	background: currentColor;
	transform: rotate(-45deg);
	transform-origin: left center;
}

.arrow-icon::after {
	content: '';
	position: absolute;
	top: 50%;
	left: 25%;
	width: 12px;
	/* 控制箭头长度 */
	height: 2px;
	/* 控制线条粗细 */
	background: currentColor;
	transform: rotate(45deg);
	transform-origin: left center;
}

/* 交互效果 */
.arrow-icon:hover {
	opacity: 0.7;
}

.arrow-icon:active {
	transform: scale(0.9);
}

.bg {
	position: absolute;
	width: 100%;
	height: 100%;
}

.container {
	height: 100%;
	width: 100%;
	margin: 0;
	padding: 0;
	position: absolute;
	top: 0px;
	left: 0px;
	display: block;
}

.check-btn1 {
	position: absolute;
	bottom: 26%;
	right: 20px;
	width: 77px;
	height: 80px;
	/* background-image: url('/images/check-btn-1.png'); */
	background-size: cover;
	z-index: 2;

}

.check-btn2 {
	position: absolute;
	bottom: 16%;
	right: 20px;
	width: 77px;
	height: 80px;
	/* background-image: url('/images/check-btn-2.png'); */
	background-size: cover;
	z-index: 2;

}

.check-btn3 {
	position: absolute;
	bottom: 6%;
	right: 20px;
	width: 77px;
	height: 80px;
	/* background-image: url('/images/check-btn-3.png'); */
	background-size: cover;
	z-index: 2;

}

.obj-name {
	width: 100%;
	position: absolute;
	top: 120px;
	font-family: Source Han Sans CN;
	font-size: 24px;
	font-weight: 540;
	text-align: center;
	color: rgba(255, 255, 255, 1);
	text-shadow: 0 0 0px #fcc300, 0 0 8px #fcc300, 0 0 16px #fcc300;
}

.obj-describe {
	width: calc(100% - 150px);
	position: absolute;
	bottom: 120px;
	font-family: Source Han Sans CN;
	font-size: 16px;
	font-weight: 400;
	text-align: left;
	color: rgba(255, 255, 255, 1);
	text-shadow: 0 0 0px #fcc300, 0 0 8px #fcc300;
	padding: 0px 100px 0px 50px;
	line-height: 1.5;
	text-indent: 2em;
}

.label-3d {
	width: 60%;
	position: absolute;
	font-family: Source Han Sans CN;
	font-size: 24px;
	font-weight: 540;
	text-align: center;
	color: rgba(255, 255, 255, 1);
	text-shadow: 0 0 0px #fcc300, 0 0 8px #fcc300, 0 0 16px #fcc300;
	background-color: rgba(100, 141, 100, 0.8);
}

.base-3d-object {
	position: absolute;
	pointer-events: auto;
	user-select: none;
	z-index: 3;
	color: #fcc300;
	font-family: Source Han Sans CN;
	font-size: 24px;
	font-weight: 540;
	text-shadow: 0 0 0px rgb(182, 99, 13), 0 0 8px rgb(182, 99, 13), 0 0 16px rgb(182, 99, 13);
	background: #33455c21;
}

.base-3d-container {
	transform-origin: 0px 0px;
	pointer-events: none;
	z-index: 1;
	top: 0px;
	overflow: hidden;
	position: absolute;
	user-select: none;
}

.base-3d-camera {
	transform-style: preserve-3d;
	user-select: none;
}

.webgl {
	height: 100%;
	width: 100%;
	margin: 0;
	padding: 0;
	position: absolute;
	top: 0px;
	left: 0px;
	display: block;
}

.description-text {
	font-size: 8px;
	word-wrap: break-word;
	white-space: normal;
	width: 80px;
	padding: 5px;
	text-indent: 2em;
}
</style>
